package com.gitee.core.ftp;

import com.google.common.collect.Sets;
import com.jcraft.jsch.ChannelSftp;
import org.joda.time.DateTime;

import java.util.Set;

/**
 * @ClassName: SftpTask
 * @Description: FTP文件同步任务
 * @author zhang_tao6
 * @date 2018年1月15日 下午5:44:03
 * @version v1.0
 * 
 */
public class SftpTask implements Runnable {

    // 机构标识
    private String instId;

    // 银行根目录
    private String bankRootDir;

    // 本地根目录
    private String localRootDir;

    // 本地连接池
    private ChannelSftpPool localPool;

    // 银行连接池
    private ChannelSftpPool bankPool;

    public SftpTask(String instId, String bankRootDir, String localRootDir, ChannelSftpPool localPool,
            ChannelSftpPool bankPool) {
        this.instId = instId;
        this.bankRootDir = bankRootDir;
        this.localRootDir = localRootDir;
        this.localPool = localPool;
        this.bankPool = bankPool;
    }

    @Override
    public void run() {
        while (true) {
            try { // 银行FTP
                ChannelSftp bankSftp;

                bankSftp = bankPool.borrowObject();

                SftpUtils bankSftpUtils = new SftpUtils(bankSftp);
                // 本地FTP
                ChannelSftp localSftp = localPool.borrowObject();
                SftpUtils localSftpUtils = new SftpUtils(localSftp);

                String yyyyMMdd = DateTime.now().toString("yyyyMMdd");
                // 渤海FTP根目录/instId/CHK/yyyyMMdd
                String bankDir = bankRootDir + instId + "/CHK/" + yyyyMMdd;
                // 本地FTP根目录/instId/CHK
                String localPDir = localRootDir + instId + "/CHK";
                // 银行文件列表
                Set<String> bankFiles = bankSftpUtils.listFiles(bankDir);
                // 本地文件列表
                Set<String> localFiles = localSftpUtils.listFiles(localPDir + "/" + yyyyMMdd);
                Set<String> difference = Sets.difference(bankFiles, localFiles);

                String tmpDir = "/tmp/" + instId + "/" + yyyyMMdd + "/";
                for (String file : difference) {
                    System.out.println("file:" + file);
                    bankSftpUtils.download(bankDir, file, tmpDir + file);
                    localSftpUtils.upload(localPDir, yyyyMMdd, tmpDir + file);
                }

                bankPool.returnObject(bankSftp);
                localPool.returnObject(localSftp);

                Thread.sleep(10000);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}
